/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;

using TypeElement = argot.TypeElement;
using TypeException = argot.TypeException;
using TypeInputStream = argot.TypeInputStream;
using TypeOutputStream = argot.TypeOutputStream;
using TypeReader = argot.TypeReader;
using TypeWriter = argot.TypeWriter;

namespace argot.common
{
	
	/// <summary>
	/// This is a basic 16-bit unsigned int value stored in big endian format.
	/// </summary>
	public class BigEndianUnsignedShort 
	:TypeReader, TypeWriter
	{
		
		public const System.String TYPENAME = "u16";
		
		public unsafe virtual System.Object Read(TypeInputStream inStream, TypeElement element)
		{
			byte[] array = new byte[2];
			
			if ( inStream.Stream.Read( array,0,2 ) < 2 )
				throw new System.IO.EndOfStreamException();

			if ( BitConverter.IsLittleEndian )
			{
				byte b = array[0]; array[0] = array[1]; array[1] = b;
			}

			fixed( byte* parray = array )
			{
				return *((System.UInt16 *)parray);
			}

		}
		

		public virtual void Write(TypeOutputStream outStream, System.Object o, TypeElement element)
		{
			int a, b, s;
			if (o is System.Int32)
			{
				s = ((System.Int32) o);
			}
			else if (o is System.Int16)
			{
				s = (int) ((System.Int16) o);
			}
			else
				throw new TypeException("BigEndianShort requires Short or Integer object");
			
			if (s < MIN || s > MAX)
				throw new TypeException("U16: value out of range:" + s);
			
			a = (s & 0xff00) >> 8;
			b = (s & 0x00ff);
			
			outStream.Stream.WriteByte((System.Byte) a);
			outStream.Stream.WriteByte((System.Byte) b);
		}
		
		public const int MIN = 0;
		public const int MAX = 65536; //2^16-1; 
	}
}